package com.itheima.tlias.controller;

import com.itheima.tlias.dto.SelectClazzDTO;
import com.itheima.tlias.po.InsertClazzParam;
import com.itheima.tlias.po.SelectClazzPageParam;
import com.itheima.tlias.po.UpdateClazzParam;
import com.itheima.tlias.service.ClazzService;
import com.itheima.tlias.util.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
@RequestMapping("/clazzs")
public class ClazzController {
    @Resource
    ClazzService clazzService;

    @GetMapping
    public ResultUtil selectClazzByPage(SelectClazzPageParam param) {
        if (Objects.isNull(param.getPage()) || Objects.isNull(param.getPageSize())) {
            return ResultUtil.fail("分页参数不存在");
        }
        return clazzService.selectClazzByPage(param);
    }

    @PostMapping
    public ResultUtil insertClazz(@Validated @RequestBody InsertClazzParam param) {
        int flag = clazzService.insertClazz(param);
        return flag == 0 ? ResultUtil.fail("添加失败") : ResultUtil.success("添加成功");
    }

    @GetMapping("{id}")
    public ResultUtil selectClazzById(@PathVariable("id")Integer id){
        SelectClazzDTO dto = clazzService.selectClazzById(id);
        return ResultUtil.success(dto);
    }

    @DeleteMapping("/{id}")
    public ResultUtil deleteClazzById(@PathVariable("id") Integer id) {
        int flag = clazzService.deleteClazzById(id);
        return flag == 0 ? ResultUtil.fail("删除失败") : ResultUtil.success("删除成功");
    }

    @PutMapping
    public ResultUtil updateClazz(@RequestBody UpdateClazzParam param){
        int flag = clazzService.updateClazz(param);
        return flag == 0 ? ResultUtil.fail("更新失败") : ResultUtil.success("修改成功");
    }

    @GetMapping("/list")
    public ResultUtil selectClazzNameById(){
        List<SelectClazzDTO> dtos = clazzService.selectClazzAll();
        return ResultUtil.success(dtos);
    }
}
